﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Interactivity;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Threading;

namespace XWord.WPF.Behaviors
{
    public class ScrollIntoViewAction : TargetedTriggerAction<ListBox>
    {
        protected override void Invoke(object parameter)
        {
            if (this.Target.SelectedItem == null)
            {
                ScrollTarget.SelectedItem = null;
                return;
            }
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                if (Mode == ScrollMode.TwoWay)
                    Target.ScrollIntoView(this.Target.SelectedItem);
                if (string.IsNullOrEmpty(ST_EqualEntity) && ScrollTarget.Items.IndexOf(this.Target.SelectedItem)>0)
                {
                    
                    ScrollTarget.ScrollIntoView(this.Target.SelectedItem);
                    return;
                }
                else if(!string.IsNullOrEmpty(ST_EqualEntity))
                {
                    var list = ScrollTarget.ItemsSource.Cast<object>().Where(e => e.GetType().GetProperty(ST_EqualEntity).GetValue(e, null).Equals(this.Target.SelectedItem));
                    if (list.Count() > 0)
                        ScrollTarget.ScrollIntoView(list.First());
                    return;
                }
                var item=ScrollTarget.ItemsSource.Cast<object>().Where(e => e.Equals(this.Target.SelectedItem));
                if (item.Count() > 0)
                {
                    ScrollTarget.ScrollIntoView(item.First());
                }
            }), DispatcherPriority.Render);
        }

        public ScrollMode Mode
        {
            get { return (ScrollMode)GetValue(ModeProperty); }
            set { SetValue(ModeProperty, value); }
        }

        public static readonly DependencyProperty ModeProperty =
            DependencyProperty.Register("Mode", typeof(ScrollMode), typeof(ScrollIntoViewAction),
            new UIPropertyMetadata(ScrollMode.TwoWay));

        public string ST_EqualEntity { get; set; }

        public ListBox ScrollTarget
        {
            get { return (ListBox)GetValue(ScrollTargetProperty); }
            set { SetValue(ScrollTargetProperty, value); }
        }


        public static readonly DependencyProperty ScrollTargetProperty =
            DependencyProperty.Register("ScrollTarget", typeof(ListBox), typeof(ScrollIntoViewAction),
            new UIPropertyMetadata(null));


    }

    public enum ScrollMode
    {
        OneWay,
        TwoWay
    }
}
